﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.ADepartment;
using B.S.BasicData.Api.Read.Dtos;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfaces;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.CommandHandler.ADepartment
{
    public class GetDepartmentHandler : IRequestHandler<GetDepartmentCommand, ApiResult<List<ADepartmentTreeDTO>>>
    {
        private readonly IBaseRepository<DepartmentModel> departRepo;
        private readonly IMapper mapper;

        public GetDepartmentHandler(IBaseRepository<DepartmentModel> departRepo, IMapper mapper)
        {
            this.departRepo = departRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<List<ADepartmentTreeDTO>>> Handle(GetDepartmentCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<ADepartmentTreeDTO>> result = new ApiResult<List<ADepartmentTreeDTO>>();

            result.Msg = "查询部门树成功";
            result.Code = ApiEnums.Success;
            result.Data = GetTree(0);

            return Task.FromResult(result);
        }

        private List<ADepartmentTreeDTO> GetTree(long parentId)
        {
          var departs = departRepo.Query().Result.Where(x => x.ParentId == parentId);
            var dtos = mapper.Map<List<ADepartmentTreeDTO>>(departs);
            foreach (var d in dtos) { 
                d.Child = GetTree(d.Id);
            }
            return dtos;    
        }
    }
}
